package com.wanggy.mystore.controller;

import com.wanggy.mystore.entity.Address;
import com.wanggy.mystore.service.IAddressService;
import com.wanggy.mystore.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddresController extends BaseController {
    @Autowired
    private IAddressService addressService;

    @PostMapping("/add_new_address")
    public JsonResult<Void> addNewAddress(Address address, HttpSession session) {
        //通过session获取uid
        Integer uid = getUidFromSession(session);
        //通过session获取username
        String username = getUsernameFromSession(session);
        //调用业务层新增收货地址
        addressService.addNewAddress(uid, username, address);

        return new JsonResult<>(OK);
    }

    @GetMapping({"/", ""})
    public JsonResult<List<Address>> getByUid(HttpSession session) {
        //获取当前用户的uid
        Integer uid = getUidFromSession(session);
        List<Address> addressList = addressService.getByUid(uid);
        return new JsonResult<>(OK, addressList);
    }

    @GetMapping("/{aid}/set_default")
    public JsonResult<Void> setDefault(HttpSession session, @PathVariable("aid") Integer aid) {
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        addressService.setDefault(aid, uid, username);
        return new JsonResult<>(OK);
    }

    @GetMapping("/{aid}/delete")
    public JsonResult<Void> delete(HttpSession session, @PathVariable("aid") Integer aid) {
        addressService.deleteByAid(aid,getUidFromSession(session),getUsernameFromSession(session));
        return new JsonResult<>(OK);
    }
}
